package com.huatai.common.httputil;

/**
 * @program: ht-system
 * @description:
 * @author: songxiude
 * @create: 2023-04-25 15:39
 **/

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.helper.DataUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.springframework.cglib.proxy.Enhancer;

public class DomMapper {
	public DomMapper() {
	}

	public static Document asDocument(ResponseSpec response) {
		return readDocument(response.asString());
	}

	public static Document readDocument(InputStream inputStream) {
		try {
			return DataUtil.load(inputStream, StandardCharsets.UTF_8.name(), "");
		} catch (IOException var2) {
			throw Exceptions.unchecked(var2);
		}
	}

	public static Document readDocument(String html) {
		return Parser.parse(html, "");
	}

	public static <T> T readValue(InputStream inputStream, final Class<T> clazz) {
		return readValue((Element)readDocument(inputStream), clazz);
	}

	public static <T> T readValue(String html, final Class<T> clazz) {
		return readValue((Element)readDocument(html), clazz);
	}

	public static <T> T readValue(final Element doc, final Class<T> clazz) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(clazz);
		enhancer.setUseCache(true);
		enhancer.setCallback(new CssQueryMethodInterceptor(clazz, doc));
		return (T) enhancer.create();
	}

	public static <T> List<T> readList(InputStream inputStream, final Class<T> clazz) {
		return readList((Element)readDocument(inputStream), clazz);
	}

	public static <T> List<T> readList(String html, final Class<T> clazz) {
		return readList((Element)readDocument(html), clazz);
	}

	public static <T> List<T> readList(Element doc, Class<T> clazz) {
		CssQuery annotation = (CssQuery)clazz.getAnnotation(CssQuery.class);
		if (annotation == null) {
			throw new IllegalArgumentException("DomMapper readList " + clazz + " mast has annotation @CssQuery.");
		} else {
			String cssQueryValue = annotation.value();
			Elements elements = doc.select(cssQueryValue);
			List<T> valueList = new ArrayList();
			Iterator var6 = elements.iterator();

			while(var6.hasNext()) {
				Element element = (Element)var6.next();
				valueList.add(readValue(element, clazz));
			}

			return valueList;
		}
	}
}

